package com.ydd.controller.home;

import com.ydd.constant.JwtClaimsConstant;
import com.ydd.constant.MessageConstant;
import com.ydd.dto.LoginAndRegDTO;
import com.ydd.entity.SysUser;
import com.ydd.entity.YddUser;
import com.ydd.exception.LoginFailedException;
import com.ydd.properties.JwtProperties;
import com.ydd.result.Result;
import com.ydd.service.SysUserService;
import com.ydd.service.YddUserService;
import com.ydd.utils.JwtUtil;
import com.ydd.vo.TokenVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Api(tags = "用户端-登录相关接口")
@RestController
@Slf4j
public class LoginController {

    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private YddUserService yddUserService;

//    @ApiOperation("管理端登录接口")
//    @PostMapping("/index/login")
//    public Result sysLogin(@RequestBody LoginAndRegDTO loginAndRegDTO){
//        log.info("管理端用户接口：{}",loginAndRegDTO);
//        SysUser sysUser = sysUserService.findByCondition(loginAndRegDTO);
//        String token;
//        if(sysUser!=null){
//            String sysUserId = sysUser.getId();
//            Map<String,Object> map = new HashMap<>();
//            map.put(JwtClaimsConstant.ADMIN_ID,sysUserId);
//            token = JwtUtil.createJWT(jwtProperties.getAdminSecretKey(), jwtProperties.getAdminTtl(), map);
//        }else{
//            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
//        }
//        return Result.success(token);
//    }

    @ApiOperation("用户端登录接口")
    @PostMapping("/api/home/index/login")
    public Result yddLogin(@RequestBody LoginAndRegDTO loginAndRegDTO){
        log.info("用户端登录接口：{}",loginAndRegDTO);
        YddUser yddUser = yddUserService.findByCondition(loginAndRegDTO);
        String token;
        if(yddUser!=null){
            Long yddUserId = yddUser.getId();
            Map<String,Object> map = new HashMap<>();
            map.put(JwtClaimsConstant.USER_ID,yddUserId);
            token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), map);
        }else{
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        return Result.success(new TokenVO(token));
    }
}
